package com.liaoyifan.core.filter;

import com.liaoyifan.core.util.RequestContext;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingRequestWrapper;

@SuppressWarnings("unused")
public class CachingRequestFilter extends OncePerRequestFilter {

    @SuppressWarnings("NullableProblems")
    @Override
    protected void doFilterInternal(
            HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        if (!this.isAsyncDispatch(request)
                && !RequestContext.isMultipartRequest(request)
                && !RequestContext.NO_BODY_METHODS.contains(request.getMethod())
                && !(request instanceof ContentCachingRequestWrapper)) {
            ContentCachingRequestWrapper contentCachingRequestWrapper =
                    new ContentCachingRequestWrapper(request, RequestContext.MAX_BODY_SIZE);
            filterChain.doFilter(contentCachingRequestWrapper, response);
            contentCachingRequestWrapper.getInputStream().readAllBytes();
            return;
        }
        filterChain.doFilter(request, response);
    }
}
